//
//  QLMOnlineBaoxiuVC.m
//  Xiaomakuaixiu
//
//  Created by 龚碧容 on 2017/10/11.
//  Copyright © 2017年 hwd. All rights reserved.
//

#import "QLMOnlineBaoxiuVC.h"
#import <AssetsLibrary/AssetsLibrary.h>
#import "QLMAddressBookModel.h"

@interface QLMOnlineBaoxiuVC ()<CNContactPickerDelegate,UIActionSheetDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate,CTAssetsPickerControllerDelegate>{
    UIButton *imageBtn;
    UILabel *nameLabel;
}
@property (nonatomic,strong) NSMutableArray *modelArray;
@end

@implementation QLMOnlineBaoxiuVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title=@"在线报修";
    
//    imageBtn=[self baocreatButton:CGRectMake(80, 64+20, 80, 44) title:@"选择图片" image:nil];
//   [self.view addSubview:imageBtn];
    
    _modelArray=[NSMutableArray array];
    
//    UIButton *contactButton=[UIButton buttonWithType:UIButtonTypeCustom];
//    [contactButton setTitle:@"选择联系人" forState:UIControlStateNormal];
//    contactButton.frame=CGRectMake(kScreen_width/2-40, 64+80, 80, 40);
//    contactButton.backgroundColor=kButtonColor;
//    contactButton.titleLabel.font=[UIFont systemFontOfSize:13.0f];
//    [contactButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
//    [contactButton addTarget:self action:@selector(contactButtonAction:) forControlEvents:UIControlEventTouchUpInside];
//    [self.view addSubview:contactButton];
    
//    nameLabel=[[UILabel alloc] initWithFrame:CGRectMake(80, 200, 200, 40)];
//    nameLabel.textColor=[UIColor greenColor];
//    nameLabel.font=[UIFont systemFontOfSize:12.0];
//    [self.view addSubview:nameLabel];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden=NO;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (UIButton *)baocreatButton:(CGRect)aFrame title:(NSString *)aTitle image:(NSString *)imageName{
    UIButton *newButton = [UIButton buttonWithType:UIButtonTypeCustom];
    newButton.frame = aFrame;
    [newButton setImage:[UIImage imageNamed:imageName] forState:UIControlStateNormal];
    [newButton setTitle:aTitle forState:UIControlStateNormal];
    [newButton setTitleColor:UIColorFromRGB(0x333333) forState:UIControlStateNormal];
    newButton.backgroundColor = [UIColor whiteColor];
    newButton.titleLabel.font=[UIFont systemFontOfSize:13.0f];
    [newButton addTarget:self action:@selector(selImageBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    return newButton;
}

- (void)selImageBtnAction:(UIButton *)btn{
    UIActionSheet *cameraSheet = [[UIActionSheet alloc]initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"相册",@"拍照", nil];
    cameraSheet.actionSheetStyle = UIActionSheetStyleAutomatic;
    [cameraSheet showInView:self.view];
}

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    
    if(buttonIndex == 0){
        CTAssetsPickerController *picker = [[CTAssetsPickerController alloc] init];
        picker.showsNumberOfAssets = YES;
        picker.delegate = self;
        [self presentViewController:picker animated:YES completion:NULL];
    }else if(buttonIndex == 1){
        if(![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]){
            return;
        }
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
        // picker.allowsEditing = YES;
        picker.sourceType = UIImagePickerControllerSourceTypeCamera;
        picker.delegate = self;
        [self presentViewController:picker animated:YES completion:nil];
    }else if(buttonIndex == 2){
        return;
    }
}

#pragma mark - UIImagepicker delegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    [picker dismissViewControllerAnimated:YES completion:^{
        UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
        [imageBtn setImage:image forState:UIControlStateNormal];
    }];
}

- (void)assetsPickerController:(CTAssetsPickerController *)picker didFinishPickingAssets:(NSArray<PHAsset*> *)assets{

    
    /** 关闭图片选择控制器*/
    [picker dismissViewControllerAnimated:YES completion:^{
        CGFloat scale = [UIScreen mainScreen].scale;
        PHImageRequestOptions *options = [[PHImageRequestOptions alloc] init];
        options.resizeMode = PHImageRequestOptionsResizeModeExact;
        options.deliveryMode = PHImageRequestOptionsDeliveryModeHighQualityFormat;

        /** 遍历选择的所有图片*/
        for (NSInteger i = 0; i < assets.count; i++) {
            PHAsset *asset = assets[i];
            CGSize size = CGSizeMake(asset.pixelWidth / scale, asset.pixelHeight / scale);
            
            /** 获取图片*/
            [[PHImageManager defaultManager] requestImageForAsset:asset
                                                       targetSize:size
                                                      contentMode:PHImageContentModeDefault
                                                          options:options
                                                    resultHandler:^(UIImage * _Nullable result, NSDictionary * _Nullable info) {
                                                        
                                                        [imageBtn setImage:result forState:UIControlStateNormal];
//                                                        [self.imageArray removeLastObject];
//                                                        [self.imageArray addObject:result];
//                                                        /** 刷新*/
//                                                        [self reload];
                                                    }];
        }
    }];

}

/** 相片的最大选择数方法*/
- (BOOL)assetsPickerController:(CTAssetsPickerController *)picker shouldSelectAsset:(PHAsset *)asset {
//    NSInteger max = 5;
//    if (picker.selectedAssets.count - 1 >= max) {
//        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"notice" message:@"feedback_more_photo" preferredStyle:UIAlertControllerStyleAlert];
//        [alert addAction:[UIAlertAction actionWithTitle:@"dialog_OK" style:UIAlertActionStyleDefault handler:nil]];
//        [picker presentViewController:alert animated:YES completion:nil];
//        return NO;
//    }
    return YES;
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/
- (void)contactButtonAction:(UIButton *)sender{
    
    if(IOS9_OR_LATER){
        __block BOOL authorization;
        CNAuthorizationStatus status = [CNContactStore authorizationStatusForEntityType:CNEntityTypeContacts];
        if (status == CNAuthorizationStatusAuthorized){
            authorization = YES;
        }else{
            CNContactStore *contactStore = [[CNContactStore alloc] init];
            [contactStore requestAccessForEntityType:CNEntityTypeContacts completionHandler:^(BOOL granted, NSError * _Nullable error) {
                if (granted) {
                    // 成功
                    authorization = YES;
                    [self _presentToContactVC];
                } else {
                    // 失败
                    authorization = NO;
                }
            }];
        }
        
        if (authorization) {
            [self _presentToContactVC];
        }
        
    }
}

- (void)_presentToContactVC{
    
    CNContactPickerViewController *contactController = [[CNContactPickerViewController alloc] init];
    contactController.delegate = self;
    contactController.displayedPropertyKeys = @[CNContactPhoneNumbersKey];
    [self presentViewController:contactController animated:YES completion:nil];
}

#pragma mark - CNContactPickerViewController delegate
- (void)contactPickerDidCancel:(CNContactPickerViewController *)picker{
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)contactPicker:(CNContactPickerViewController *)picker didSelectContactProperty:(CNContactProperty *)contactProperty{
    
    [_modelArray removeAllObjects];
    
    QLMAddressBookModel *addressBookModel=[[QLMAddressBookModel alloc] init];
    addressBookModel.givenName=contactProperty.contact.givenName;
    addressBookModel.middleName=contactProperty.contact.middleName;
    addressBookModel.familyName=contactProperty.contact.familyName;
    addressBookModel.organizationName=contactProperty.contact.organizationName;
    addressBookModel.phoneNumbers=contactProperty.contact.phoneNumbers;
    
    [_modelArray addObject:addressBookModel];
    if (addressBookModel.phoneNumbers.count==0) {
        return;
    }
    CNLabeledValue *labeledValue=(CNLabeledValue *)addressBookModel.phoneNumbers[0];
    CNPhoneNumber *phoneValue = labeledValue.value;
    NSString *phoneNumber = phoneValue.stringValue;
//    NSString *label = [CNLabeledValue localizedStringForLabel:labeledValue.label];

    nameLabel.text=[NSString stringWithFormat:@"%@ %@ %@%@",phoneNumber,addressBookModel.givenName,addressBookModel.middleName,addressBookModel.familyName];
}

@end
